import {ref, computed} from 'vue'
import {NCard, NButton, NProgress, NSpace, NTag, NPopover, NTooltip, NIcon, NDropdown, NModal} from 'naive-ui'
import {useXianLuStore} from '#imports'
import {ZhiwuStatus, ZhiwuDataType} from '~/utils/zhiwilist'
import {FarmToolType, farmTools} from '~/utils/farmTools'
import {landLevels} from '~/utils/land'
import ZhongzhiModal from './ZhongzhiModal'
import '~/assets/style/landItem.css'

const LandType = Object.freeze({
    READY: "ready",    // 可种植
    NOTREADY: "notReady",  // 不可种植
    ZHONGZHI: "zhongzhi",    // 正在种植
    UPGRADING: "upgrading", // 正在升级
})

export default defineNuxtComponent({
    name: "地块",
    props: {
        data: {
            type: Object,
            default: () => ({})
        }
    },
    setup(props) {
        const store = useXianLuStore()
        const upgradeProgress = ref(0)
        const upgradeTimer = ref(null)
        const isUpgrading = ref(false)
        const isDeveloping = ref(false) // 添加开发中状态
        const showZhongzhiModal = ref(false)
        const harvestMessage = ref('')
        const showHarvestMessage = ref(false)
        
        // 添加倒计时相关状态
        const countdownTime = ref(0) // 总倒计时时间（秒）
        const remainingTime = ref(0) // 剩余时间（秒）
        const countdownTimer = ref(null) // 倒计时定时器
        
        // 植物生长加速状态
        const growthBoost = ref({
            bug: 0,      // 除虫加成
            water: 0,    // 浇水加成
            fertilizer: 0 // 施肥加成（影响产量）
        })
        
        // 工具使用消息
        const toolMessage = ref('')
        const showToolMessage = ref(false)

        // 计算当前土地状态
        const status = computed(() => {
            if (isUpgrading.value) {
                return LandType.UPGRADING
            }
            if (isDeveloping.value) {
                return LandType.UPGRADING // 开发中也显示为升级中状态
            }
            if (props.data.status === LandType.NOTREADY) {
                return LandType.NOTREADY
            }
            if (props.data.zhiwu) {
                return LandType.ZHONGZHI
            }
            return LandType.READY
        })

        // 添加确认弹窗状态
        const showDevelopConfirm = ref(false)
        const showUpgradeConfirm = ref(false)

        // 开发土地
        const developLand = () => {
            // 检查金币是否足够
            const lingshiItem = store.itemList.find(item => item.type === 'lingshi')
            if (!lingshiItem || lingshiItem.amount < props.data.developCost) {
                // 显示灵石不足消息
                toolMessage.value = `灵石不足，需要${props.data.developCost}个灵石`
                showToolMessage.value = true
                setTimeout(() => {
                    showToolMessage.value = false
                }, 3000)
                return
            }
            
            // 扣除灵石
            lingshiItem.amount -= props.data.developCost
            
            // 模拟开发过程
            isDeveloping.value = true
            
            // 设置倒计时（20秒）
            countdownTime.value = 20
            remainingTime.value = 20

            // 启动倒计时
            if (countdownTimer.value) {
                clearInterval(countdownTimer.value)
            }
            
            countdownTimer.value = setInterval(() => {
                remainingTime.value--
                
                if (remainingTime.value <= 0) {
                    clearInterval(countdownTimer.value)
                    isDeveloping.value = false
                    // 更新土地状态
                    if (props.data && typeof props.data === 'object') {
                        props.data.status = 'ready'
                        props.data.level = 1
                    }
                }
            }, 1000) // 每秒更新一次
        }

        // 升级土地
        const upgradeLand = () => {
            if (props.data.level >= 10) {
                // 已达到最高等级
                return
            }

            showUpgradeConfirm.value = true
        }

        // 确认升级土地
        const confirmUpgradeLand = () => {
            // 关闭确认弹窗
            showUpgradeConfirm.value = false
            
            // 获取当前等级对应的升级所需灵石
            const currentLevel = props.data.level
            const levelInfo = landLevels.find(level => level.level === currentLevel)
            
            if (!levelInfo) {
                return
            }
            
            // 检查灵石是否足够
            const lingshiItem = store.itemList.find(item => item.type === 'lingshi')
            if (!lingshiItem || lingshiItem.amount < levelInfo.lingshi) {
                // 显示灵石不足消息
                toolMessage.value = `灵石不足，需要${levelInfo.lingshi}个灵石`
                showToolMessage.value = true
                setTimeout(() => {
                    showToolMessage.value = false
                }, 3000)
                return
            }
            
            // 扣除灵石
            lingshiItem.amount -= levelInfo.lingshi
            
            // 模拟升级过程
            isUpgrading.value = true
            
            // 设置倒计时（25秒）
            countdownTime.value = 25
            remainingTime.value = 25

            // 启动倒计时
            if (countdownTimer.value) {
                clearInterval(countdownTimer.value)
            }
            
            countdownTimer.value = setInterval(() => {
                remainingTime.value--
                
                if (remainingTime.value <= 0) {
                    clearInterval(countdownTimer.value)
                    isUpgrading.value = false
                    // 更新土地等级
                    if (props.data && typeof props.data === 'object') {
                        props.data.level += 1
                    }
                }
            }, 1000) // 每秒更新一次
        }

        // 铲除植物
        const removePlant = () => {
            if (props.data && typeof props.data === 'object') {
                props.data.zhiwu = null
                // 重置生长加速状态
                resetGrowthBoost()
            }
        }

        // 打开种植弹窗
        const openZhongzhiModal = () => {
            showZhongzhiModal.value = true
        }

        // 确认种植
        const confirmZhongzhi = (zhiwu: ZhiwuDataType) => {
            if (props.data && typeof props.data === 'object') {
                // 创建一个新的植物对象，避免直接修改原始数据
                const newZhiwu = JSON.parse(JSON.stringify(zhiwu))
                // 设置初始状态为发芽
                newZhiwu.status = ZhiwuStatus.FAYA
                // 初始化生长进度
                newZhiwu.growthProgress = 0
                // 初始化生长加速状态
                newZhiwu.growthBoost = {
                    bug: 0,
                    water: 0,
                    fertilizer: 0
                }
                // 将植物添加到土地
                props.data.zhiwu = newZhiwu

                // 这里应该调用store的方法来记录种植信息
                // 模拟获得种植经验
                store.addExp(newZhiwu.exp.zhongzhi || 10)
                
                // 重置生长加速状态
                resetGrowthBoost()
            }
        }

        // 收获植物
        const harvestPlant = () => {
            if (props.data && props.data.zhiwu && props.data.zhiwu.status === ZhiwuStatus.CHENGSHU) {
                // 获取产品
                let harvestItems = []
                props.data.zhiwu.product.forEach(product => {
                    // 计算施肥后的产量
                    const fertilizeBonus = growthBoost.value.fertilizer / 100
                    const finalAmount = Math.floor(product.amount * (1 + fertilizeBonus))
                    
                    store.addItem({
                        type: product.type,
                        name: product.name,
                        amount: finalAmount,
                        description: product.description
                    })
                    harvestItems.push(`${product.name} x${finalAmount}`)
                })

                // 显示收获消息
                harvestMessage.value = `收获了: ${harvestItems.join(', ')}`
                showHarvestMessage.value = true
                setTimeout(() => {
                    showHarvestMessage.value = false
                }, 3000)

                // 获得经验
                store.addExp(props.data.zhiwu.exp.shouhua || 20)

                // 清空土地
                props.data.zhiwu = null
                
                // 重置生长加速状态
                resetGrowthBoost()
            }
        }

        // 获取植物状态文本
        const getPlantStatusText = (status) => {
            switch (status) {
                case ZhiwuStatus.FAYA:
                    return '发芽中'
                case ZhiwuStatus.SHENGZHANG:
                    return '生长中'
                case ZhiwuStatus.KAIHUA:
                    return '开花中'
                case ZhiwuStatus.CHENGSHU:
                    return '已成熟'
                default:
                    return '未知状态'
            }
        }

        // 获取植物生长进度
        const getGrowthProgress = (zhiwu) => {
            if (!zhiwu || !zhiwu.growthProgress) return 0
            let result = 0
            switch (zhiwu.status) {
                case ZhiwuStatus.FAYA:
                    result = Number(((zhiwu.growthProgress / zhiwu.growTime.faya) * 100).toFixed(0))
                    break
                case ZhiwuStatus.SHENGZHANG:
                    result =  Number(((zhiwu.growthProgress / zhiwu.growTime.shengzhang) * 100).toFixed(0))
                    break
                case ZhiwuStatus.KAIHUA:
                    result = Number(((zhiwu.growthProgress / zhiwu.growTime.kaihua) * 100).toFixed(0))
                    break
                default:
                    result = 100
            }
            return result
        }
        
        // 重置生长加速状态
        const resetGrowthBoost = () => {
            growthBoost.value = {
                bug: 0,
                water: 0,
                fertilizer: 0
            }
            
            // 同步重置植物对象中的生长加速状态
            if (props.data && props.data.zhiwu && props.data.zhiwu.growthBoost) {
                props.data.zhiwu.growthBoost = {
                    bug: 0,
                    water: 0,
                    fertilizer: 0
                }
            }
        }
        
        // 使用农田工具
        const useFarmTool = (tool: FarmToolType) => {
            if (!props.data.zhiwu || props.data.zhiwu.status === ZhiwuStatus.CHENGSHU) {
                return
            }
            
            // 检查背包中是否有该工具
            const toolInBag = store.itemList.find(item => item.name === tool.name && item.amount > 0)
            
            if (!toolInBag) {
                toolMessage.value = `你没有${tool.name}！`
                showToolMessage.value = true
                setTimeout(() => {
                    showToolMessage.value = false
                }, 3000)
                return
            }
            
            // 减少道具数量
            toolInBag.amount--
            
            // 应用工具效果
            switch (tool.effect.type) {
                case 'bug':
                    growthBoost.value.bug = tool.effect.value
                    break
                case 'water':
                    growthBoost.value.water = tool.effect.value
                    break
                case 'fertilizer':
                    growthBoost.value.fertilizer = tool.effect.value
                    break
            }
            
            // 同步生长加速状态到植物对象
            if (props.data.zhiwu) {
                if (!props.data.zhiwu.growthBoost) {
                    props.data.zhiwu.growthBoost = {
                        bug: 0,
                        water: 0,
                        fertilizer: 0
                    }
                }
                props.data.zhiwu.growthBoost.bug = growthBoost.value.bug
                props.data.zhiwu.growthBoost.water = growthBoost.value.water
                props.data.zhiwu.growthBoost.fertilizer = growthBoost.value.fertilizer
            }
            
            // 显示使用消息
            toolMessage.value = `使用了${tool.name}，${tool.description}`
            showToolMessage.value = true
            setTimeout(() => {
                showToolMessage.value = false
            }, 3000)
        }
        
        // 获取可用工具下拉菜单选项
        const getToolOptions = () => {
            return farmTools.map(tool => ({
                label: `${tool.icon || ''} ${tool.name}`,
                key: tool.id,
                disabled: !store.itemList.some(item => item.name === tool.name && item.amount > 0),
            }))
        }
        
        // 处理工具选择
        const handleToolSelect = (key: string) => {
            const selectedTool = farmTools.find(tool => tool.id === key)
            if (selectedTool) {
                useFarmTool(selectedTool)
            }
        }
        
        // 获取当前生长加速状态文本
        const getBoostStatusText = () => {
            const boosts = []
            if (growthBoost.value.bug > 0) {
                boosts.push(`除虫+${growthBoost.value.bug}%`)
            }
            if (growthBoost.value.water > 0) {
                boosts.push(`浇水+${growthBoost.value.water}%`)
            }
            if (growthBoost.value.fertilizer > 0) {
                boosts.push(`施肥+${growthBoost.value.fertilizer}%`)
            }
            
            return boosts.length > 0 ? boosts.join(', ') : '无'
        }

        // 种植状态渲染
        const zhongzhiRender = () => {
            const zhiwu = props.data.zhiwu
            return <NCard title={`${zhiwu.name} - ${getPlantStatusText(zhiwu.status)}`} class="land-item zhongzhi"
                          header-class={"!p-4px text-center"} content-class={"!p-4px  flex-center"}>
                <NSpace vertical>

                    {/* 生长进度 */}
                    {zhiwu.status !== ZhiwuStatus.CHENGSHU && (
                        <div>
                            <div>生长进度:</div>
                            <NProgress type="line" percentage={getGrowthProgress(zhiwu)}/>
                        </div>
                    )}
                    
                    {/* 生长加速状态 */}
                    <div>
                        <div>加速状态: {getBoostStatusText()}</div>
                    </div>

                    {/* 工具按钮和成熟状态 */}
                    <NSpace>
                        {zhiwu.status !== ZhiwuStatus.CHENGSHU ? (
                            <>
                                <NDropdown options={getToolOptions()} onSelect={handleToolSelect}>
                                    <NButton type="info" size="small">使用道具</NButton>
                                </NDropdown>
                                <NButton type="warning" size="small" onClick={removePlant}>铲除植物</NButton>
                            </>
                        ) : (
                            <NButton type="success" onClick={harvestPlant}>收获</NButton>
                        )}
                    </NSpace>

                    {/* 工具使用消息 */}
                    {showToolMessage.value && (
                        <div class="tool-message">{toolMessage.value}</div>
                    )}

                    {/* 收获消息 */}
                    {showHarvestMessage.value && (
                        <div class="harvest-message">{harvestMessage.value}</div>
                    )}
                </NSpace>
            </NCard>
        }

        // 不可种植状态渲染
        const notReadyRender = () => {
            return <NCard title="未开发土地" class="land-item not-ready" header-class={"!p-4px text-center"}
                          content-class={"!p-4px flex-center"}>
                <NSpace vertical>
                    <NPopover trigger="hover">
                        {{
                            trigger: () => <NButton type="primary" onClick={developLand}>开发</NButton>,
                            default: () => `需要${props.data.developCost}个灵石`
                        }}
                    </NPopover>
                </NSpace>
            </NCard>
        }

        // 待种植状态渲染
        const readyRender = () => {
            return <NCard title={`${props.data.level}级土地`} class="land-item ready" header-class={"!p-4px text-center"}
                          content-class={"!p-4px flex-center"}>
                <NSpace vertical>
                    <div>该土地已准备好，可以种植</div>
                    <NSpace justify="center">
                        <NButton type="success" onClick={openZhongzhiModal}>种植</NButton>
                        {props.data.level < 10 && (
                            <NPopover trigger="hover">
                                {{
                                    trigger: () => <NButton type="info" onClick={upgradeLand}>升级</NButton>,
                                    default: () => {
                                        const currentLevel = props.data.level
                                        const levelInfo = landLevels.find(level => level.level === currentLevel)
                                        return levelInfo ? `需要${levelInfo.lingshi}个灵石` : '无法升级'
                                    }
                                }}
                            </NPopover>
                        )}
                    </NSpace>
                    
                    {/* 升级确认弹窗 */}
                    <NModal
                        show={showUpgradeConfirm.value}
                        preset="dialog"
                        title="确认升级土地"
                        content={(() => {
                            const currentLevel = props.data.level
                            const levelInfo = landLevels.find(level => level.level === currentLevel)
                            return levelInfo ? 
                                `确定要花费 ${levelInfo.lingshi} 个灵石将土地升级到 ${currentLevel + 1} 级吗？` : 
                                '无法升级土地'
                        })()}
                        positiveText="确认"
                        negativeText="取消"
                        onPositiveClick={confirmUpgradeLand}
                        onNegativeClick={() => showUpgradeConfirm.value = false}
                    />
                </NSpace>
            </NCard>
        }

        // 升级中状态渲染
        const upgradingRender = () => {
            // 格式化剩余时间
            const formatTime = (seconds) => {
                const mins = Math.floor(seconds / 60)
                const secs = seconds % 60
                return `${mins}:${secs < 10 ? '0' + secs : secs}`
            }
            
            const actionType = props.data.status === LandType.NOTREADY ? '开发' : '升级'
            
            return <NCard title={`土地${actionType}中`} class="land-item upgrading" header-class={"!p-4px text-center"}
                          content-class={"!p-4px flex-center"}>
                <NSpace vertical>
                    <div>正在{actionType}中，剩余时间: {formatTime(remainingTime.value)}</div>
                </NSpace>
            </NCard>
        }

        return () => {
            return <>
                {/* 种植弹窗 */}
                <ZhongzhiModal
                    value={showZhongzhiModal.value}
                    onUpdate:value={(val) => showZhongzhiModal.value = val}
                    landId={props.data.id}
                    landLevel={props.data.level}
                    onConfirm={confirmZhongzhi}
                />

                {/* 土地渲染 */}
                {(() => {
                    switch (status.value) {
                        case LandType.ZHONGZHI:
                            return zhongzhiRender()
                        case LandType.NOTREADY:
                            return notReadyRender()
                        case LandType.READY:
                            return readyRender()
                        case LandType.UPGRADING:
                            return upgradingRender()
                        default:
                            return readyRender()
                    }
                })()}
            </>
        }
    }
})